package com.wemei.auto.ui.helper.loadsir

import android.view.View
import android.widget.RelativeLayout
import com.kingja.loadsir.callback.Callback
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.wemei.auto.ui.R
import com.wemei.auto.ui.ext.dp
import com.wemei.auto.ui.utils.Logger


fun View.registerLoadSir(listener: (() -> Unit)? = null): LoadService<*> {
    return LoadSirHelper.register(this, listener = listener)
}

object LoadSirHelper {

    fun registerNotDefault(target: Any, callback: Callback? = null, listener: (() -> Unit)? = null): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.let { builder.addCallback(it) }
        return builder.build().register(target) { listener?.invoke() }
    }

    fun registerMultipleNotDefault(
        target: Any,
        callback: MutableList<Callback>? = null,
        listener: (() -> Unit)? = null,
    ): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.forEach { builder.addCallback(it) }
        return builder.build().register(target) { listener?.invoke() }
    }

    fun register(
        target: Any,
        callback: ArrayList<Callback>? = null,
        defaultCallback: Class<out Callback> = LoadingCallback::class.java,
        listener: (() -> Unit)? = null,
    ): LoadService<*> {
        val builder = LoadSir.beginBuilder()
        callback?.forEach { builder.addCallback(it) }
        builder.addCallback(LoadingCallback())
            .addCallback(ErrorCallback())
            .addCallback(EmptyCallback())
            .addCallback(NotNetworkCallback())
            .setDefaultCallback(defaultCallback)
        return builder.build().register(target) { listener?.invoke() }
    }

    fun changePosition(mLoadService: LoadService<*>?, top: Int) {
        try {
            mLoadService?.run {
                setCallBack(EmptyCallback::class.java) { _, view ->
                    doChangePosition(
                        view.findViewById(R.id.ll_text),
                        top
                    )
                }
                setCallBack(LoadingCallback::class.java) { _, view ->
                    doChangePosition(
                        view.findViewById(R.id.ll_loading),
                        top
                    )
                }
                setCallBack(ErrorCallback::class.java) { _, view ->
                    doChangePosition(
                        view.findViewById(R.id.ll_text),
                        top
                    )
                }
            }
        } catch (e: Exception) {
            Logger.e(e)
        }
    }

    private fun doChangePosition(view: View, top: Int) {
        (view.layoutParams as RelativeLayout.LayoutParams).apply {
            removeRule(RelativeLayout.CENTER_IN_PARENT)
            addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
            topMargin = top.dp
        }
    }
}